const express = require('express')
const path = require('path')
const cors = require('cors')
const adminRouter = require('./src/routes/admin')
const apiRouter = require('./src/routes/api')
const { auth } = require('./src/middlewares/auth')
const { ErrorModel } = require('./src/utils/resModel')
const app = express()
const port = 8000
require('dotenv').config({ path: path.resolve('./src/conf/', '.env') })
require('./src/db')()

app.use(cors({}))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use((req, res, next) => {
  console.log(`${req.url} - ${req.method}`)
  next()
})

app.use('/admin', adminRouter)
app.use('/api', auth, apiRouter)

app.use((err, req, res, next) => {
  // console.log(err)
  const ERROR_CODE_MESSAGE = {
    11000: '当前账号已经注册'
  }
  res.status(!err.status ? 500 : err.status).send({
    code: -1,
    message: ERROR_CODE_MESSAGE.hasOwnProperty(err.code)
      ? ERROR_CODE_MESSAGE[err.code]
      : err.message === 'jwt malformed'
      ? '伪造授权token'
      : err.message
  })
})

app.listen(port, (err) => {
  if (err) throw err
  console.log(`this serve is running in http://localhost:${port}`)
})
